<template>
  <el-dialog title="编辑进项发票" :visible.sync="dialogVisible" width="1600px" :close-on-click-modal="false"
    :modal-append-to-body="false" v-drag2anywhere>
    <el-form :model="formData" ref="formData" size="mini" label-width="100px" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="发票类型:" prop="type">
            <el-select v-model="formData.type" placeholder="请选择发票类型" style="width: 100%;">
              <el-option label="普通发票" value="普通发票"></el-option>
              <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票号码" prop="num">
            <el-input v-model="formData.num" placeholder="发票号码"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="发票代码">
            <el-input v-model="formData.code" placeholder="发票代码"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="开票日期:" prop="date">
            <el-date-picker type="datetime" value-format="yyyy-MM-dd H:m:s" placeholder="开票日期" v-model="formData.date"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="销售单位:" prop="seller">
            <el-select v-model="formData.seller" filterable style="width: 100%;" clearable>
              <el-option v-for="(item,index) in sellerlist" :label="item.title" :key="item.index" :value="item.title">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
           <el-form-item label="发票用途:" prop="usage">
           <el-select v-model="formData.usage" placeholder="发票用途" style="width: 100%;" clearable allow-create
            filterable>
            <el-option label="物资发票" value="物资发票"></el-option>
            <el-option label="费用发票" value="费用发票"></el-option>
           </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="购方单位:" prop="buyer">
            <el-select v-model="formData.buyer" filterable style="width: 100%;" clearable>
              <el-option v-for="(item,index) in buyerlist" :label="item.name" :key="item.index" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否代开票">
            <div style="display: flex;">
              <div style="margin-right: 10px;"><el-checkbox v-model="formData.daikai"></el-checkbox></div>
              <div v-if="formData.daikai" style="width: 300px;"><el-input v-model="formData.daikaititle"
                  style="width: 100%;" placeholder="代开税务局名称"></el-input></div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col>
          <el-form-item label="发票明细:">
            <div style="display: flex;">
              <div style="flex: 1;">标 <span style="color:#FF0000">*</span> 字段为必填项</div>
              <div>
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增明细</el-button>
              </div>
            </div>
            <div style="height:200px; overflow-y: auto;border:1px solid #EEEEEE">
              <el-table :data="formData.goods" border>
                <el-table-column label="序号" type="index" align="center" width="50px"></el-table-column>
                <el-table-column label="稅收类目" width="150px">
                  <template v-slot="scope">
                    <el-select filterable v-model="scope.row.taxname" clearable :title="scope.row.taxname">
                      <el-option v-for="(item,index) in taxclassify" :key="index" :label="item.name" :value="item.name" >
                        <div style="width: 500px;display: flex;" :title="item.keyword">
                          <div style="flex: 1;">{{item.name}}</div>
                          <span style="color:#d1d1d1;font-size: 12px;"> {{item.keyword}}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="货物或应税劳务、服务名称">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 货物或应税劳务、服务名称
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.title" :rows="1" type="textarea" placeholder="货物名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="规格型号" width="140px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.model" :rows="1" type="textarea" placeholder="规格型号"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" width="90px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.unit" placeholder="单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="95px">
                  <template slot="header">
                    数量
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.count" @change="handleCountChange(scope.$index,scope.row)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="center" width="95px" show-overflow-tooltip>
                  <template v-slot="scope">
                    {{scope.row.price}}
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="total" width="160px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 金额
                  </template>
                  <template v-slot="scope">
                    <el-input-number v-model="scope.row.total" :precision="2"
                      @change="handleTotalChange(scope.$index,scope.row)" style="width: 100%;"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="税率" prop="rate" width="95px" align="center">
                  <template v-slot="scope">
                    <el-select v-model="scope.row.rate" placeholder="请选择税率"
                      @change="handleRateChange(scope.$index,scope.row)">
                      <el-option label="免税" value="0"></el-option>
                      <el-option label="1%" value="0.01"></el-option>
                      <el-option label="1.5%" value="0.15"></el-option>
                      <el-option label="3%" value="0.03"></el-option>
                      <el-option label="5%" value="0.05"></el-option>
                      <el-option label="6%" value="0.06"></el-option>
                      <el-option label="9%" value="0.09"></el-option>
                      <el-option label="12%" value="0.12"></el-option>
                      <el-option label="13%" value="0.13"></el-option>
                      <el-option label="16%" value="0.16"></el-option>
                      <el-option label="17%" value="0.17"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="税额" align="center" prop="tax" width="150px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 税额
                  </template>
                  <template v-slot="scope">
                    <el-input-number v-model="scope.row.tax" :precision="2" style="width: 100%;"
                      @change="handleTaxChanged(scope.$index,scope.row)"></el-input-number>
                  </template>
                </el-table-column>

                <el-table-column label="价税总额" align="center" prop="sum" width="95px">
                  <template v-slot="scope">
                    {{parseFloat(scope.row.sum).toFixed(2)}}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60px" align="center">
                  <template v-slot="scope">
                    <el-button circle icon="el-icon-delete" size="mini" type="danger"
                      @click="handleDelete(scope.$index,scope.row)">
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div>
              <div style="float: right; margin:5px;">
                <span style="margin-right:15px">金额: {{formData.total}}</span>
                <span style="margin-right:15px">税额: {{formData.tax}}</span>
                <span style="margin-right:15px">合计: {{formData.sum}}</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票上传:" prop="attach">
            <el-upload list-type="picture-card" ref="upload" :file-list="upconfig.imgList" :action="upconfig.action"
              :headers="upconfig.headers" :accept="upconfig.accept" :limit="upconfig.limit" :on-change="handleChange"
              :auto-upload="false" :on-remove="handleRemove" :on-exceed="handleLimit" multiple
              :on-preview="handlePreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="5" v-model="formData.memo" maxlength="255" show-word-limit
              placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

      </el-row>
    </el-form>


    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSaveAttach" v-if="formData.buy_bindstatus==1?true:false">保存(仅附件)</el-button>
      <el-button type="primary" size="medium" @click="handleSave" :disabled="formData.buy_bindstatus==1?true:false">保存发票</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { parse } from 'semver';
  export default {
    data() {
      return {
        checkAttach(rule, value, callback) {
          if (this.upconfig.fileList.length != 0) {
            return callback("请选择发票上传");
          } else {
            return true;
          }
        },
        taxclassify: [],
        formData: {
          type: '增值税专用发票',
          num: '',
          seller: '',
          buyer:'',
          date: '',
          code: '',
          total: 0,
          tax: 0,
          usage:'物资发票',
          sum: 0,
          goods: [],
          memo: '',
          daikai: false,
          daikaititle: ''
        },
        sellerlist: [],
        buyerlist:[],
        dialogVisible: false,
        //文件上传相关变量
        upconfig: {
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png,.pdf',
          limit: 5,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          rids: [], //要删除的id
          action: ""
        },
        rules: {
          buyer: [{
            required: true,
            message: '购方不能为空!',
            trigger: 'blur'
          }],
          usage: [{
            required: true,
            message: '发票用途不能为!',
            trigger: 'blur'
          }],
          seller: [{
            required: true,
            message: '销方不能为空!',
            trigger: 'blur'
          }],
          date: [{
            required: true,
            message: '开票时间不能为空!',
            trigger: 'blur'
          }],

          type: [{
            required: true,
            message: '请选择发票类型!',
            trigger: 'change'
          }],
          num: [{
            required: true,
            message: '请正确填写发票号码!',
            trigger: 'blur'
          }]
        },



      }
    },
    methods: {
      init(index,data) {
        this.index=index;
        this.formData=data;
        this.formData.daikai=this.formData.daikai==1? true:false;
        this.upconfig.imgList=this.formData.attach;
        this.upconfig.fileList=[];
        this.loadSellers();
        this.loadBuyers();
        this.loadTaxClasasify();
      },
      autoImport(data) {
        this.formData = data;
        this.upconfig.fileList = [];
        this.handleRefreshBottomSum();

      },
      handleSaveAttach(){
        var fd = new FormData();
        fd.append("id",this.formData.id);
        fd.append("rids",this.upconfig.rids.join(","));
        //附件上传
        let fid = 0;
        this.upconfig.fileList.forEach(file => {
          if (file.raw) {
            fd.append("file" + fid, file.raw);
            fid++;
          }
        });

        this.$axiosUploader.post("api/admin/buyticket/update_attach", fd).then(res => {
          if (res.status == 200 && res.data.code) {
            this.$message.success({
              message: res.data.msg,
              duration: 1500,
              showClose: true
            });
            this.upconfig.imgList = res.data.attachlist;

            this.dialogVisible = false;
            this.$emit("completeHandler",this.index,this.formData,res.data.attachlist);
            this.$refs.upload.clearFiles();
          } else {
            this.$message.error({
              message: res.data.msg,
              duration: 1500,
              showClose: true
            });
          }
        });


      },
      handleTotalChange(index, data) {
         var count=this.formData.goods[index].count==""? 1: parseFloat(this.formData.goods[index].count);
        this.formData.goods[index].sum = this.format2Number(parseFloat(this.formData.goods[index].total) + parseFloat(
          this.formData.goods[
            index].tax), 2);
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this
          .formData.goods[index].rate)) / this.formData.goods[index].count, 7);
        this.handleRefreshBottomSum();

      },
      handleTaxChanged(index, data) {
             var count=this.formData.goods[index].count==""? 1: parseFloat(this.formData.goods[index].count);
        this.formData.goods[index].sum = this.format2Number(parseFloat(this.formData.goods[index].total) + parseFloat(
          this.formData.goods[
            index].tax), 2);
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this
          .formData.goods[index].rate)) / count, 7);
        this.handleRefreshBottomSum();
      },
      handleCountChange(index, data) {
        var count=this.formData.goods[index].count==""? 1: parseFloat(this.formData.goods[index].count);
        this.formData.goods[index].sum = this.format2Number(parseFloat(this.formData.goods[index].total) + parseFloat(
          this.formData.goods[index].tax), 2);
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this
          .formData.goods[index].rate)) / count, 7);
        this.handleRefreshBottomSum();
      },
      handleRateChange(index, row) {
          var count=this.formData.goods[index].count==""? 1: parseFloat(this.formData.goods[index].count);
        this.formData.goods[index].sum = this.format2Number(parseFloat(this.formData.goods[index].total) + parseFloat(
          this.formData.goods[index].tax), 2);
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this
          .formData.goods[index].rate)) / count, 7);
        this.handleRefreshBottomSum();
      },
      handleRefreshBottomSum() {
        this.formData.total = 0;
        this.formData.tax = 0;
        this.formData.goods.forEach(item => {
          this.formData.total += parseFloat(item.total);
          this.formData.tax += parseFloat(item.tax);
          item.total = this.format2Number(item.total, 2);
        })
        this.formData.tax = this.formData.tax.toFixed(2);
        this.formData.sum = (parseFloat(this.formData.total) + parseFloat(this.formData.tax)).toFixed(2);
      },
      /***********************文件上传区域开始****************/
      //文件数量超限提示
      handleLimit: function() {
        this.$message.warning("最多可上传" + this.upconfig.limit + "个文件");
      },
      handleChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "pdf"];
        var sizeok = file.size / 1024 / 1024 < 5;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过5M");
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }

        this.upconfig.fileList = list;
      },
      // 文件列表移除文件时的钩子
      handleRemove: function(file, fileList) {
        console.log(file);
        if (file.id) { //如果存储 id即为已经上传好的图片
          this.upconfig.rids.push(file.id);
        }
        this.upconfig.fileList = fileList;
      },
      /***********************文件上传区域结束****************/

      format2Number(value, len) {
        var f = parseFloat(value);
        return parseFloat(f.toFixed(parseInt(len)));
      },

      loadTaxClasasify() {
        this.axios.post("api/common/taxclassify/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.taxclassify = res.data.list;
          }
        });
      },
     loadBuyers(){
       this.axios.post("api/admin/account/list").then(res => {
         if (res.status == 200 && res.data.code == 0) {
           this.buyerlist = res.data.list;
         }
       });
     },
     loadSellers() {
       this.axios.post("api/admin/buysupplier/list_item").then(res => {
         if (res.status == 200 && res.data.code == 0) {
           this.sellerlist = res.data.list;
         }
       });
     },
      handlePreview(file) {
        console.log("yulan");
      },
      handleSave() {
        this.$refs.formData.validate(ok => {
          if (ok) {
            if (this.formData.goods.length <= 0) {
              this.$message.error({
                message: "采购明细不能为空!",
                duration: 1500,
                showClose: true
              });
              return;
            }
            //检测物品信息
            let index = 1;
            let verifyOk = true;
            for (var i = 0; i < this.formData.goods.length; i++) {
              index = (i + 1);
              if (this.formData.goods[i].taxname == "") {
                this.$message.error({
                  message: '第' + index + "行 请选择相应的税收分类!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].title == "") {
                this.$message.error({
                  message: '第' + index + "行 货物或应税劳务、服务名称填写有误!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              }
            }

            if (!verifyOk) {
              return;
            }

            if(this.formData.goods.length>0 && this.formData.sum==0){
              this.$message.error({
                message: "开票明细含税总额不能为0.00元",
                duration: 1500,
                showClose: true
              });
              return;
            }
            //提交
            var fd = new FormData();
            fd.append("id",this.formData.id);
            fd.append("rids",this.upconfig.rids.join(","));
            fd.append("type",this.formData.type);
            fd.append("num", this.formData.num);
            fd.append("code", this.formData.code);
            fd.append("date", this.formData.date);
            fd.append("seller", this.formData.seller);
            fd.append("buyer", this.formData.buyer);
            fd.append("daikai", this.formData.daikai ? 1 : 0);
            fd.append("daikaititle", this.formData.daikai ? this.formData.daikaititle : '');
            fd.append("goods", JSON.stringify(this.formData.goods));
            fd.append("total", this.formData.total);
            fd.append("tax", this.formData.tax);
            fd.append("sum", this.formData.sum);
            fd.append("memo", this.formData.memo);
            fd.append("usage",this.formData.usage);
            //附件上传
            let fid = 0;
            this.upconfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("file" + fid, file.raw);
                fid++;
              }
            });

            this.$axiosUploader.post("api/admin/buyticket/update", fd).then(res => {
              if (res.status == 200 && res.data.code) {
                this.$message.success({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
                this.upconfig.imgList = res.data.attachlist;

                this.dialogVisible = false;
                this.$emit("completeHandler",this.index,this.formData,res.data.attachlist);
                this.$refs.upload.clearFiles();
              } else {
                this.$message.error({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
              }
            });

          }
        });
      },
      handleDelete(index, row) {
        this.$confirm("确定要删除此项吗?", "提示").then(() => {
          this.formData.goods.splice(index, 1);
        })
      },
      handleAdd() {
        this.formData.goods.push({
          id: -1,
          taxname:'',
          title: '',
          model: '',
          unit: '',
          count: 1,
          price: '0.00',
          total: 0,
          rate: '0.13',
          tax: 0,
          sum: 0,
        });
      }
    }
  }
</script>

<style>
</style>
